/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;

public class CaptchaServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");
        if (action.equals("getCaptcha")) {
             String cap=request.getSession().getAttribute("captcha").toString();
             PrintWriter out= response.getWriter();
             out.write(cap);
             out.close();
        } else {

            int width = 300;
            int height = 60;
            int fontSize = 26;
            int xGap = 30;
            int yGap = 25;

            String fontName = "Arial";
            Color gradiantStartColor = new Color(60, 60, 60); // dark grey
            Color gradiantEndColor = new Color(140, 140, 140); // light grey




            String[] newData = {"sdSF2", "ASff2", "#fs612", "Agfd@6", "!fg3DS"};
            Random r = new Random();
            int index = Math.abs(r.nextInt()) % newData.length;
            String captcha = newData[index];
            request.getSession().setAttribute("captcha", captcha);

            BufferedImage bufferedImage = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = bufferedImage.createGraphics(); // vẽ ảnh vào buffered image

            RenderingHints rh = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON); // khử răng cưa

            rh.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY); // nâng chất lượng hình

            g2d.setRenderingHints(rh);

            GradientPaint gp = new GradientPaint(0, 0,
                    gradiantStartColor, 0, height / 2, gradiantEndColor, true);

            g2d.setPaint(gp); // màu nền startcolor
            g2d.fillRect(0, 0, width, height); // lồng màu nền vào nhau

            for (int i = 0; i < width - 10; i = i + 25) {
                int p = Math.abs(r.nextInt()) % width;
                int q = Math.abs(r.nextInt()) % width;
                int colorIndex = Math.abs(r.nextInt()) % 200;
                g2d.setColor(new Color(colorIndex, colorIndex, colorIndex)); // màu chữ
                g2d.drawLine(p, 0, i + p, q); // vẽ các đường cắt hình
                g2d.drawLine(p, 0, i + 25, height);
            }

            int x = 0;
            int y = 0;

            for (int i = 0; i < captcha.length(); i++) {
                Font font = new Font(fontName, Font.BOLD, fontSize);
                g2d.setFont(font);
                x += xGap + (Math.abs(r.nextInt()) % 15);
                y = yGap + Math.abs(r.nextInt()) % 20;
                g2d.drawChars(captcha.toCharArray(), i, 1, x, y);
            } //ghi từng chữ, vị trí i, length là 1, tọa độ x,y

            g2d.dispose();

            response.setContentType("image/png"); // chỉnh content type là imange/png
            OutputStream os = response.getOutputStream();
            ImageIO.write(bufferedImage, "png", os); // viết data từ bufferImage vào outputStream, gửi binary data về phía client
            os.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
